<template>
    <div class="goods-add-form">
        <!-- 出库基本信息区块 -->
        <div class="section">
            <h2 class="section-title" style="display:flex">
                {{ warehouse_codego }}
                <div class="action-buttons" style="position: relative;left:850px; top:-10px;">
                    <el-button @click="handleEdit(mainForm.othoutord_audit_statua)">
                        编辑
                    </el-button>
                    <el-button @click="handleDelete">
                        删除
                    </el-button>
                    <el-button @click="handleExamine(mainForm.othoutord_audit_statua)">
                        审核
                    </el-button>
                </div>
            </h2>

            <table style="width: 100%; border-collapse: collapse;border: none;">
                <tbody>
                    <!-- 出库类型 -->
                    <tr>
                        <td style="padding: 10px 0px; width: 15%; color: #666;">出库类型</td>
                        <td style="padding: 10px 0px 10px 10px; width: 20%;">
                            <span v-if="!isEditing">{{ othoutord_type }}</span>
                            <el-select v-else v-model="editForm.othoutord_type" style="width:100%">
                                <el-option v-for="item in dict_labelSwer1212" :key="item.dict_value"
                                    :label="item.dict_label" :value="item.dict_value" />
                            </el-select>
                        </td>

                        <!-- 出库仓库 -->
                        <td style="padding: 10px 0px 10px 10px; width: 15%; color: #666;">出库仓库</td>
                        <td style="padding: 10px 0px 10px 10px; width: 20%;">
                            <span v-if="!isEditing">{{ warehouse_name }}</span>
                            <el-input v-else v-model="editForm.warehouse_name" />
                        </td>

                        <!-- 出库库区 -->
                        <td style="padding: 10px 0px; color: #666;">出库库区</td>
                        <td style="padding: 10px 0px 10px 10px;">
                            <span v-if="!isEditing">{{ mainForm.zone_name }}</span>
                            <el-input v-else v-model="editForm.zone_name" />
                        </td>
                    </tr>

                    <!-- 出库状态 -->
                    <tr>
                        <td style="padding: 10px 0px; width: 15%; color: #666;">出库状态</td>
                        <td style="padding: 10px 0px 10px 10px; width: 20%;">
                            {{ statusText }}
                        </td>

                        <!-- 出库员 -->
                        <td style="padding: 10px 0px 10px 10px; width: 15%; color: #666;">出库员</td>
                        <td style="padding: 10px 0px 10px 10px; width: 20%;">
                            <span v-if="!isEditing">{{ mainForm.othoutord_wkeep }}</span>
                            <el-input v-else v-model="editForm.othoutord_wkeep" />
                        </td>

                        <!-- 出库时间 -->
                        <td style="padding: 10px 0px; color: #666;">出库时间</td>
                        <td style="padding: 10px 0px 10px 10px;">
                            <span v-if="!isEditing">{{ formatDate(mainForm.othoutord_time) }}</span>
                            <el-date-picker v-else v-model="editForm.othoutord_time" type="datetime"
                                value-format="YYYY-MM-DD HH:mm:ss" style="width:100%" />
                        </td>
                    </tr>

                    <!-- 审核信息行（不可编辑） -->
                    <tr>
                        <td style="padding: 10px 0px; width: 15%; color: #666;">审核状态</td>
                        <td style="padding: 10px 0px 10px 10px; width: 20%;">{{
                            getStatusText(mainForm.othoutord_audit_statua) }}</td>
                        <td style="padding: 10px 0px 10px 10px; width: 15%; color: #666;">审核人</td>
                        <td style="padding: 10px 0px 10px 10px; width: 20%;">{{ mainForm.othoutord_audit_by }}</td>
                        <td style="padding: 10px 0px; color: #666;">审核时间</td>
                        <td style="padding: 10px 0px 10px 10px;">{{ formatDate(mainForm.othoutord_audit_time) }}</td>
                    </tr>

                    <!-- 创建信息行（不可编辑） -->
                    <tr>
                        <td style="padding: 10px 0px; color: #666;">创建人</td>
                        <td style="padding: 10px 0px 10px 10px;">{{ mainForm.create_by }}</td>
                        <td style="padding: 10px 0px 10px 10px; color: #666;">创建时间</td>
                        <td style="padding: 10px 0px 10px 10px;min-width: 180px;">{{ formatDate(mainForm.create_time) }}
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>

        <!-- 出库产品明细区块 -->
        <div class="section">
            <h2 class="section-title" style="display:flex">出库产品明细</h2>

            <el-table :data="tableData" border style="width: 90%"
                :header-cell-style="{ textAlign: 'center', background: '#f5f7fa', fontWeight: 'bold', position: 'sticky', top: 0 }"
                :cell-style="{ textAlign: 'center' }">
                <el-table-column prop="pro_name" label="货品名称" width="130" />
                <el-table-column prop="pro_code" label="货品编号" width="100" />
                <el-table-column prop="pro_brand" label="品牌" width="100" />
                <el-table-column prop="pro_model" label="规格型号" width="100" />
                <el-table-column label="单位" width="70">
                    <template #default="scope">
                        <span>{{ statusValue(scope.row.unitmeas_id) }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="location_name" label="出库库位" width="130" />
                <el-table-column prop="inventory_numder" label="未出库数量" width="100" />
                <el-table-column prop="othwrproddt_numder" label="出库数量" width="110" />
                <el-table-column prop="pro_sale_price" label="出库单价" width="100" />
                <el-table-column label="出库总金额" width="202">
                    <template #default="scope">
                        <span>{{ (Number(scope.row.othwrproddt_numder || 0) * Number(scope.row.pro_sale_price ||
                            0)).toFixed(2) }}</span>
                    </template>
                </el-table-column>
            </el-table>
            <div class="summary-row">
                <span>合计</span>
                <div class="summary-values">
                    <span>出库总数量：{{ totalQuantity }}</span>
                    <span>出库总金额：{{ totalAmount.toFixed(2) }}</span>
                    <span>出库产品成本总额：{{ totalCost.toFixed(2) }}</span>
                </div>
            </div>
        </div>
    </div>

    <!-- 审核状态 -->
    <el-dialog v-model="centerDialogVisible" width="385" align-center header-align="left">
        <template #header>
            <div style="text-align: left; font-size: 16px; font-weight: bold;">
                审核
            </div>
        </template>
        <hr>
        <div style="text-align: left; padding: 10px 0px;">
            <p>审核结果</p>
            <div class="my-2 ml-4">
                <el-radio-group v-model="auditStatus">
                    <el-radio value="1">通过</el-radio>
                    <el-radio value="2">驳回</el-radio>
                </el-radio-group>
            </div>
            <div>
                <p>审核意见</p>
                <el-input v-model="auditOpinion" style="width: 350px; height: 90px;"
                    :autosize="{ minRows: 4, maxRows: 4 }" type="textarea" placeholder="请输入" />
            </div>
        </div>
        <hr>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="close">取消</el-button>
                <el-button type="primary" @click="updateAudit">
                    确定
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import axios from 'axios';
import { useWarehouseStore } from '@/storejs/warehouseStore';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import dayjs from 'dayjs';

const router = useRouter();

// 表格数据
const tableData = ref([]);

// 控制审核状态的显示
const centerDialogVisible = ref(false);

const auditStatus = ref('1'); // 审核状态
const auditOpinion = ref(''); // 审核意见
const isEditing = ref(false);

// 主表数据
const mainForm = ref({
    othoutord_status: '',
    othoutord_wkeep: '',
    othoutord_time: '',
    othoutord_code_Associated: '',
    zone_name: '',
    create_by: '',
    create_time: '',
    othoutord_audit_by: '',
    othoutord_audit_time: '',
    othoutord_audit_statua: '',
    warehouse_code: '',
    zone_code: '',
    othoutord_id:0,
});

// 单位字典
const dict_labelSwer = ref([]);
// 出库类型字典
const dict_labelSwer1212 = ref([]);

// 页面跳转获取数据
const warehouseStore = useWarehouseStore();
const warehouse_codego = ref(warehouseStore.othoutord_code || '');

const othoutord_type = ref('');
const warehouse_name = ref('');

// 状态文本映射
const statusMap = {
    0: '未出库',
    1: '已出库',
    2: '部分出库'
};

// 获取状态标签类型
const getStatusText = (status) => {
    switch (status) {
        case '0': return '待审核';
        case '1': return '已审核';
        case '2': return '驳回';
        default: return '未知状态';
    }
};

// 计算状态文本
const statusText = computed(() => {
    return statusMap[mainForm.value.othoutord_status] || '未知状态';
});

// 日期格式化
const formatDate = (dateString) => {
    if (!dateString) return '';
    try {
        const date = new Date(dateString);
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        return `${year}-${month}-${day}`;
    } catch (error) {
        console.error('日期格式化错误:', error);
        return dateString;
    }
};

// 计算出库总数量
const totalQuantity = computed(() => {
    return tableData.value.reduce((sum, item) => {
        return sum + (Number(item.othwrproddt_numder) || 0);
    }, 0).toFixed(2);
});

// 计算出库总金额
const totalAmount = computed(() => {
    return tableData.value.reduce((sum, item) => {
        const quantity = Number(item.othwrproddt_numder || 0);
        const price = Number(item.pro_sale_price || 0);
        return sum + (quantity * price);
    }, 0);
});

// 计算出库总成本
const totalCost = computed(() => {
    return tableData.value.reduce((sum, item) => {
        const quantity = Number(item.othwrproddt_numder || 0);
        const cost = Number(item.pro_cost_price || 0);
        return sum + (quantity * cost);
    }, 0);
});

// 单位值转换
function statusValue(row) {
    if (!row) return '无';
    const unit = dict_labelSwer.value.find((d) => d.dict_value == row);
    return unit ? unit.dict_label : '无';
}

// 查询产品明细
function select() {
    axios.get('http://localhost:5181/api/Inv_othoutord/Inv_trf_SelectDetail', {
        params: {
            Othoutord_code: warehouse_codego.value
        },
        headers: {
            authorization: `Bearer ${localStorage.getItem('token')}`
        }
    }).then((res) => {
        tableData.value = res.data;
    }).catch((err) => {
        console.error(err);
    });
}

// 获取单位字典
function getClassify() {
    axios.get('http://localhost:5181/api/Dict/Get_Dict_Datas', {
        params: {
            dict_type: 'db_measure'
        },
        headers: {
            authorization: `Bearer ${localStorage.getItem('token')}`
        }
    }).then((result) => {
        dict_labelSwer.value = result.data;
    }).catch((err) => {
        console.error(err);
    });
}

// 获取出库类型字典
function getClassify121() {
    axios.get('http://localhost:5181/api/Dict/Get_Dict_Datas', {
        params: {
            dict_type: 'inv_othoutord'
        },
        headers: {
            authorization: `Bearer ${localStorage.getItem('token')}`
        }
    }).then((result) => {
        dict_labelSwer1212.value = result.data;
    }).catch((err) => {
        console.error(err);
    });
}

// 查询主表信息
function handle() {
    axios.get('http://localhost:5181/api/Inv_othoutord/Inv_trf_SelectCode', {
        params: {
            Othoutord_code: warehouse_codego.value
        },
        headers: {
            authorization: `Bearer ${localStorage.getItem('token')}`
        }
    }).then((res) => {
        if (res.data && res.data.length > 0) {
            const firstItem = res.data[0];
            mainForm.value = {
                othoutord_status: firstItem.othoutord_status,
                othoutord_wkeep: firstItem.othoutord_wkeep,
                othoutord_time: firstItem.othoutord_time,
                othoutord_code_Associated: firstItem.othoutord_code_Associated || '',
                zone_name: firstItem.zone_name || '',
                create_by: firstItem.create_by,
                create_time: firstItem.create_time,
                othoutord_audit_by: firstItem.othoutord_audit_by,
                othoutord_audit_time: firstItem.othoutord_audit_time,
                othoutord_audit_statua: firstItem.othoutord_audit_statua,
                warehouse_code: firstItem.warehouse_code,
                zone_code: firstItem.zone_code,
                othoutord_id: firstItem.othoutord_id,
            };

            warehouse_name.value = firstItem.warehouse_name || '';

            // 设置出库类型文本
            const typeItem = dict_labelSwer1212.value.find(d => d.dict_value == firstItem.othoutord_type);
            othoutord_type.value = typeItem ? typeItem.dict_label : '';
        }
    }).catch((error) => {
        console.error('请求失败:', error);
    });
}

// 修改--判断审核状态
function handleEdit(othoutord_audit_statua) {
    if (othoutord_audit_statua === '1') {
        ElMessage.error('订单已审核，不可修改');
    } else {
        isEditing.value = true;
    }
}

// 取消审核按钮
function close() {
    centerDialogVisible.value = false;
    auditStatus.value = '1';
    auditOpinion.value = '';
}

var othoutord_code_update = ref('');
// 仓库编码
var weahouse_code = ref('');
// 库位编码
var zone_code = ref('');

// 获取详情单的信息
const currentOrderDetails = ref([]);

// 控制审核状态的显示
function handleExamine(othoutord_audit_statua) {
    if (othoutord_audit_statua === '1') {
        ElMessage.info(`订单${warehouse_codego.value}已审核,不可以再次审核`);
    } else {
        // 显示
        centerDialogVisible.value = true;
        othoutord_code_update.value = warehouse_codego.value;
        weahouse_code.value = mainForm.value.warehouse_code;
        zone_code.value = mainForm.value.zone_code;

        // 加载该订单的明细数据
        loadOrderDetails(othoutord_code_update.value);
    }
}

function loadOrderDetails(othoutord_code) {
    axios.get('http://localhost:5181/api/Inv_othoutord/inv_OthoutproddtlSelecControllert', {
        params: { Othoutord_code: othoutord_code },
        headers: { authorization: `Bearer ${localStorage.getItem('token')}` }
    }).then(res => {
        currentOrderDetails.value = res.data;
    }).catch(err => {
        console.error('加载订单明细失败:', err);
    });
}

/// 修改审核状态
function updateAudit() {
    if (auditStatus.value !== "1" && auditStatus.value !== "2") {
        ElMessage.error('请选择审核状态');
        return;
    }
    axios.put(
        'http://localhost:5181/api/Inv_othoutord/Inv_othoutord_examineUpdate',
        {
            Othoutord_code: othoutord_code_update.value,
            Othoutord_audit_by: localStorage.getItem('userLName'),
            Othoutord_audit_time: dayjs().format('YYYY-MM-DDTHH:mm:ss.SSSZ'),
            othoutord_audit_statua: auditStatus.value,
            othoutord_audit_opinion: auditOpinion.value,
        },
        {
            headers: {
                authorization: `Bearer ${localStorage.getItem('token')}`
            }
        }
    ).then((res) => {
        if (res.data > 0) {
            if (auditStatus.value === '1') {
                ElMessage.success('审核通过');
                // 关闭弹窗
                close();
                // 刷新数据
                select();
                setTimeout(handle, 300);
                // 订单审核通过之后,修改仓库容量

                // 修改仓库内量
                const updateRequests = currentOrderDetails.value.map(item => ({
                    warehouse_code: weahouse_code.value,
                    zone_code: zone_code.value,
                    location_code: item.location_code,
                    Othoutproddtl_numder: Number(item.othwrproddt_numder) || 0
                }));

                Weahous_update(updateRequests);
            } else {
                ElMessage.error('审核驳回');
                // 关闭弹窗
                close();
                // 刷新数据
                select();
                setTimeout(handle, 300);
            }
        } else {
            ElMessage.error('审核失败');
        }
    }).catch((err) => {
        console.info(err);
    });
}





// 删除操作
const handleDelete = async () => {
    try {
        if(mainForm.value.othoutord_audit_statua === '1'){
            ElMessage.info(`订单${warehouse_codego.value}已审核,不可以进行删除`)
            return;
        }


        // 第一步：先弹出确认框
        const confirmResult = await ElMessageBox.confirm(
            `你确定要删除单号为 ${warehouse_codego.value} 的出库单记录吗？`,
            '提示',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        );

        if (confirmResult === 'confirm') {
            // 根据ID发起删除请求
            const res = await axios.put(
                'http://localhost:5181/api/Inv_othoutord/Inv_othoutord_delete',
                null, // 请求体为空
                {
                    params: { othoutord_id: mainForm.value.othoutord_id },
                    headers: {
                        authorization: `Bearer ${localStorage.getItem('token')}`
                    }
                }
            );

            if (res.data > 0) {
                ElMessage.success('删除成功');
                router.push('/main/Inv/Inv_othoutordVue');
            } else {
                ElMessage.error('删除失败');
            }
        }
    } catch (err) {
        if (err === 'cancel') {
            console.log('用户取消删除');
        } else {
            console.error('删除出错:', err);
            ElMessage.error('删除失败，请稍后重试');
        }
    }
};



// 保存出库单
function handleSave() {
    console.log('保存出库单');
}

// 关闭页面
function handleClose() {
    router.back();
}

onMounted(() => {
    select();
    getClassify();
    getClassify121();
    // 确保字典加载完成后再查询主表信息
    setTimeout(handle, 300);
});
</script>

<style scoped>
.goods-add-form {
    padding: 20px;
    background-color: #fff;
    position: relative;
}

.section {
    margin-bottom: 20px;
    padding: 20px;
    border: 1px solid #ebeef5;
    border-radius: 4px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.section-title {
    font-size: 16px;
    font-weight: bold;
    margin-bottom: 15px;
    padding-bottom: 10px;
    border-bottom: 1px solid #ebeef5;
}

.label {
    display: inline-block;
    width: 80px;
    text-align: right;
    margin-right: 10px;
}

.summary-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 40px;
    line-height: 40px;
    padding: 0 10px;
    border-top: none;
    width: 89.2%;
}

.summary-values {
    display: flex;
    gap: 20px;
}

.button-group {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
    margin-top: 20px;
}

.el-table {
    margin-top: 10px;
}

.el-row {
    margin-bottom: 10px;
}
</style>
